<template>

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
    <el-button type="primary" @click="isEditable = !isEditable">
        {{ isEditable ? '锁定' : '编辑' }}
    </el-button>
    <!--<el-dialog v-model="dialogFormVisible" v-if="dialogFormVisible" title="添加资产类型" width="58%"> -->
    <!--   <Add :departmentdata="departmentdata" :assetForm="assetForm" @addSubmit="handleSubmit"></Add> -->
    <!-- </el-dialog>-->
    <el-button type="text" :disabled="!isEditable" @click="addDepartment" >
        <el-icon><Plus /></el-icon>
        新增部门
    </el-button>
    </div>  
    <el-table
        :data="departmentData"
        style="width: 100%"
        row-key="id"
        border
        clearable
        
        :tree-props="{ children: 'children', hasChildren: 'hasChildren'}"
    >
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="parent_id" label="上级部门" />
        <!--<el-table-column prop="description" label="描述" />-->
        <el-table-column prop="createdAt" label="创建时间" />
        <el-table-column prop="updatedAt" label="更新时间" />
        <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
            <el-button
            type="primary"
            :icon="Edit"
            size="small"
            :disabled="!isEditable"
            @click="openEditDialog(scope.row)"
            title="编辑部门"
            >编辑</el-button>
            <el-button
            type="danger"
            :icon="Edit"
            size="small"
            :disabled="!isEditable"
            @click="removeType(scope.row.id)"
            title="删除部门"
            >删除</el-button>
        </template>
        </el-table-column>
  </el-table>
    <el-dialog v-model="dialogFormVisible" title="新增部门" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输部门名称" />
        </el-form-item>
        <el-form-item label="上级部门" prop="parent_id">
          <el-tree-select
            v-model="form.parent_id"
            :data="rootType"
            check-strictly
            :props="{ label: 'name', value: 'id', children: 'children'}"
            clearable
            placeholder="请选择父分类（可不选）"
          />
        </el-form-item>
        
      </el-form>

      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog
    v-model="dialogEditVisible"
    :title="修改资产分类"
    width="500px"
    >
    <el-form :model="form" label-width="80px">
        <el-form-item label="分类名称">
        <el-input v-model="form.typeName" />
        </el-form-item>
        <el-form-item label="父分类" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="rootCategories"
            :props="{ label: 'typeName', value: 'id', children: 'children' }"
            clearable
            placeholder="请选择父分类（可不选）"
          />
        </el-form-item>
        <el-form-item label="分类编码">
        <el-input v-model="form.typeCode" />
        </el-form-item>
        <el-form-item label="描述">
        <el-input v-model="form.description" type="textarea" />
        </el-form-item>
    </el-form>
    <template #footer>
        <el-button @click="dialogEditVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUpdateType">保存</el-button>
    </template>
    </el-dialog>
</template>
<script setup>

import {toRefs,onBeforeMount,onMounted,reactive,ref,computed} from "vue"
import { ElMessage,ElForm, ElFormItem, ElInput, ElButton,ElMessageBox } from 'element-plus';
import { Plus,Minus } from '@element-plus/icons-vue'
import { getDepartmentListInfoHandler,addDepartmentListInfoHandler,updateDepartmentListInfoHandler,delDepartmentListInfoHandler } from "../../api/department.js"
import { base64Decode } from "../../utils/base64.js"
const data = reactive({
    departmentData: [{ "parent_id": "", "name": ""}]
})
const isEditable = ref(false)
const dialogFormVisible = ref(false)
const dialogEditVisible = ref(false)
const {departmentData} = toRefs(data)
const formRef = ref(null)

const form = ref({
  id: null,
  parent_id: null,
  name: '',
  
})
// 过滤出主类型，避免选择子类型方法
// function getRootType(treeData) {
//  return treeData
//    .filter(item => Number(item.parent_id) === 0)
//    .map(item => {
//      return {
//        ...item,
//        children: [] // 清空子节点，只显示一级
//      }
//    })
// }
function normalizeTree(data) {
  return data.map(item => {
    return {
      ...item,
      children: item.children ? normalizeTree(item.children) : []
    }
  })
}
function getRootType(treeData, parent_id = 0) {
  return treeData
    .filter(item => Number(item.parent_id) === parent_id)
    .map(item => {
      return {
        ...item,
        children: getRootType(treeData, item.id) // 递归挂子部门
      }
    })
}
const rootType = computed(() => normalizeTree(departmentData.value || []))
const loadConfig = async()=>{
    try {
        const response = await getDepartmentListInfoHandler()
        if (response?.data?.data) {
          const result=response.data.data
          const base64String = result.queryData
          const decodedBytes = atob(base64String);
          // 将字节串转换为 Uint8Array
          const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));
          // 使用 TextDecoder 解码为字符串
          const decoder = new TextDecoder("utf-8");
          const decodedString = decoder.decode(uint8Array);
          console.log("departmentinfo===========+++++++++",decodedString)
          //window.localStorage.setItem("menus",decodedString)
          //const md5Hash = md5(decodedString+'menus_list');
          //window.localStorage.setItem("md5Hash",md5Hash)     
          departmentData.value=JSON.parse(decodedString)
          //console.log("departmentinfo=======---------------------====+++++++++",departmentdata)
          // typeData.value = base64Decode(response.data.data.queryData)
          //typeData.value =response.data.data.queryData
          console.log("departmentData==========20250919",departmentData.value)
        }
    }
    catch(error){
        console.error("获取部门数据失败:", err)
        ElMessage({
                    message: error?.response?.data?.message || "查询失败，请重试",
                    type: 'error',
        })
    }
}
const addDepartment=()=>{
    form.value = { parent_id: null,name: ''}
    dialogFormVisible.value=true
}
const submitForm = async() => {
    try{
        const valid = await formRef.value.validate()
        if(valid){
            console.log('新增分类数据:', form.value)
            const res = await addDepartmentListInfoHandler(form.value)
            if (res.data) {
                console.log("res.data====20250821",res.data)
                ElMessage({
                message: res.data.message,
                type: 'success'})
            }
            dialogFormVisible.value = false
            await loadConfig()
        }
    } catch(error){
        console.error("添加失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "添加失败，请重试",
                    type: 'error',
        })
    }
  
}
const removeType=async(id)=>{
    try {
        console.log("id=======20250813",id)
        const intId = Number(id)
        const response = await delKnowledgeTypeInfoHandler(intId)
        
        if (response.data) {
            ElMessage({
                    message: response.data.message,
                    type: 'success',
            })
            console.log("delcategoryData==========20250821",response.data)
            await loadConfig()
            
        }
    } catch(error) {
        console.error("删除失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "删除失败，请重试",
                    type: 'error',
        })
        // throw err // 如果需要让调用方知道错误
    }
    
}
const openEditDialog=(row)=>{
    console.log("row======20250813",row)
    form.value={...row}
    dialogEditVisible.value = true
}
const saveUpdateType=async()=>{
    try {
        const id=form.value.id
        console.log("==============20250822",id)

        const res = await updateKnowledgeTypeInfoHandler(id,form.value)
        if (res.data){
            ElMessage({
                    message: res.data.message,
                    type: 'success',
            })
            console.log("updatetypeData==========20250822",res.data)
            dialogEditVisible.value = false
            await loadConfig()
        }
    }catch(error){
        console.error("更新失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "更新失败，请重试",
                    type: 'error',
        })
    }
}
onMounted(()=>{
  loadConfig()
})
</script>